package com.rongc.client.core.pay.wxpay;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;

import com.rongc.client.core.Constants;
import com.rongc.client.core.utils.ActivityUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.Map;

/**
 * Created by Bruce on 2017/2/9.
 */
public class WxpayHelper {
    private static IWXAPI api;

    public interface onWxpayPaylistener{
        public void payResult(String result);
    }

    public static IWXAPI getInstent(Context context){
        if(api == null) {
            api = WXAPIFactory.createWXAPI(context, Constants.WXAPP_ID, false);
        }
        return api;
    }

    public static void pay(final Map<String,String> wxstr, final Activity act, final onWxpayPaylistener listener){

        try {
            new AsyncTask<Void, Void, Map<String,String>>() {
                @Override
                protected Map<String,String> doInBackground(Void... param) {
                    Map<String,String> result = null;

                    try {
                        PayReq req = new PayReq();
                        try{
                            req.appId = wxstr.get("appid");
                            req.partnerId = wxstr.get("partnerid");
                            req.prepayId = wxstr.get("prepayid");
                            req.packageValue = wxstr.get("_package");
                            req.nonceStr = wxstr.get("noncestr");
                            req.timeStamp = wxstr.get("timestamp");
                            req.sign = wxstr.get("sign");

                        }catch (Exception e){
                            ActivityUtils.toast("微信支付订单解析错误");
                        }

                        api.registerApp(Constants.WXAPP_ID);
                        api.sendReq(req);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return result;
                }

                @Override
                protected void onPostExecute(Map<String,String> result) {
                    super.onPostExecute(result);
                    System.out.println("wx result:"+result);
                    if(listener!=null){
                        listener.payResult(result == null ? "":result.get("resultStatus"));
                    }
                }
            }.execute();
        } catch (Exception e) {
            e.printStackTrace();
            if(listener!=null) listener.payResult(null);
        }

    }

}
